package cn.heyige.backend.controller;

import cn.heyige.backend.ai.AiService;
import cn.heyige.backend.annotation.RequireVip;
import cn.heyige.backend.common.CommResponse;
import cn.heyige.backend.dto.AiInterpretRequest;
import cn.heyige.backend.dto.AiInterpretResponse;
import cn.heyige.backend.dto.BatchAiInterpretRequest;
import cn.heyige.backend.dto.BatchAiInterpretResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/ai")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "AI智能解读服务", description = "基于AI的卦象智能解读服务")
public class AiController {
    
    private final AiService aiService;
    
    @PostMapping("/interpret")
    @Operation(summary = "获取AI智能解读", description = "根据卦象和问题获取AI智能解读")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public CommResponse<AiInterpretResponse> interpret(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody AiInterpretRequest request) {
        try {
            log.info("AI解读请求，卦象: {}, 问题: {}, AI模型: {}", 
                    request.getHexagramCode(), request.getQuestion(), request.getAiModel());
            
            // 使用现有的AiService进行解读
            String hexagramName = convertCodeToName(request.getHexagramCode());
            String aiResult = aiService.interpretDivination(hexagramName, null, request.getQuestion(), request.getAiModel());
            
            // 构建响应数据
            AiInterpretResponse response = buildAiInterpretResponse(aiResult, request);
            
            return CommResponse.ok(response);
        } catch (Exception e) {
            log.error("AI解读失败", e);
            return CommResponse.fail(500, "AI解读失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/batch-interpret")
    @Operation(summary = "批量AI解读", description = "批量处理多个卦象解读（VIP功能）")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    @RequireVip(message = "批量AI解读需要VIP会员权限")
    public CommResponse<BatchAiInterpretResponse> batchInterpret(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody BatchAiInterpretRequest request) {
        try {
            log.info("批量AI解读请求，数量: {}, AI模型: {}", 
                    request.getRequests().size(), request.getAiModel());
            
            // TODO: 实现批量AI解读逻辑
            // 1. 验证VIP权限
            // 2. 检查批量处理限制
            // 3. 并发处理多个解读请求
            // 4. 汇总结果和统计信息
            
            // 模拟响应数据
            List<BatchAiInterpretResponse.BatchInterpretResult> results = request.getRequests().stream()
                    .map(req -> {
                        AiInterpretResponse.InterpretationContent interpretation = 
                                AiInterpretResponse.InterpretationContent.builder()
                                        .summary(req.getHexagramCode() + "预示" + req.getQuestion() + "发展顺利")
                                        .build();
                        
                        return BatchAiInterpretResponse.BatchInterpretResult.builder()
                                .success(true)
                                .hexagramCode(req.getHexagramCode())
                                .interpretation(interpretation)
                                .build();
                    })
                    .toList();
            
            BatchAiInterpretResponse response = BatchAiInterpretResponse.builder()
                    .batchId("batch_" + System.currentTimeMillis())
                    .processedCount(request.getRequests().size())
                    .failedCount(0)
                    .results(results)
                    .totalCost(0.05)
                    .processingTime(3.2)
                    .build();
            
            return CommResponse.ok(response);
        } catch (Exception e) {
            log.error("批量AI解读失败", e);
            return CommResponse.fail(500, "批量解读失败: " + e.getMessage());
        }
    }
    
    private String convertCodeToName(String hexagramCode) {
        // 简单的编码到名称的转换，实际项目中应该有完整的映射表
        return hexagramCode.replace("_WEI_", "为").replace("TIAN", "天").replace("DI", "地")
                .replace("SHUI", "水").replace("HUO", "火").replace("SHAN", "山")
                .replace("ZE", "泽").replace("FENG", "风").replace("LEI", "雷")
                .toLowerCase();
    }
    
    private AiInterpretResponse buildAiInterpretResponse(String aiResult, AiInterpretRequest request) {
        // 构建详细解读
        AiInterpretResponse.InterpretationContent.DetailedInterpretation detailed = 
                AiInterpretResponse.InterpretationContent.DetailedInterpretation.builder()
                        .general(aiResult)
                        .career("事业方面的具体分析")
                        .finance("财运方面的具体分析")
                        .health("健康方面的具体分析")
                        .relationship("感情方面的具体分析")
                        .build();
        
        // 构建幸运元素
        AiInterpretResponse.InterpretationContent.LuckyElements luckyElements = 
                AiInterpretResponse.InterpretationContent.LuckyElements.builder()
                        .colors(List.of("红色", "金色"))
                        .directions(List.of("南方", "西北方"))
                        .numbers(List.of(2, 6, 9))
                        .materials(List.of("金属", "水晶"))
                        .times(List.of("9:00-11:00", "15:00-17:00"))
                        .build();
        
        // 构建解读内容
        AiInterpretResponse.InterpretationContent interpretation = 
                AiInterpretResponse.InterpretationContent.builder()
                        .summary(aiResult.length() > 100 ? aiResult.substring(0, 100) + "..." : aiResult)
                        .detailed(detailed)
                        .suggestions(List.of("把握机遇", "保持乐观"))
                        .warnings(List.of("谨慎行事"))
                        .timeline(Map.of())
                        .luckyElements(luckyElements)
                        .build();
        
        // 构建使用信息
        AiInterpretResponse.UsageInfo usage = AiInterpretResponse.UsageInfo.builder()
                .tokens(aiResult.length())
                .cost(0.01)
                .build();
        
        return AiInterpretResponse.builder()
                .interpretationId("ai_" + System.currentTimeMillis())
                .aiModel(request.getAiModel())
                .interpretationLevel(request.getInterpretationLevel())
                .generatedAt(LocalDateTime.now())
                .interpretation(interpretation)
                .confidence(0.8)
                .sources(List.of("易经原文", "现代解读", "AI分析"))
                .cached(false)
                .usage(usage)
                .build();
    }
}